<template>
  <div>
    <h1>{{id?'编辑':'新建'}}文章</h1>
    <el-form @submit.native.prevent="saveArticle" ref="form" :model="model" label-width="80px">
      <el-form-item label="文章分类">
        <el-select v-model="model.categories" multiple>
          <el-option v-for="item in articlecategory" :key="item._id" :value="item._id" :label="item.title"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="文章标题">
        <el-input v-model="model.title"></el-input>
      </el-form-item>
      <el-form-item label="文章内容">
        <!-- <el-input v-model="model.body"></el-input> -->
        <vue-editor v-model="model.body" useCustomImageHandler @image-added="handleImageAdded"></vue-editor>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit" @click="onSubmit">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>


<script>
import {VueEditor} from 'vue2-editor'
  export default {
    props:{
      id:{}
    },
    components:{
      VueEditor
    },
    data() {
      return {
        model: {},
        category:'',
        pagedata:[],
        articlecategory:[],
        htmlForEditor: ""
      }
    },
    created() {
      this.id && this.feach();
      this.feachCategory()
    },
    methods: {
      async handleImageAdded(file, Editor, cursorLocation, resetUploader){
        var formData = new FormData();
        formData.append("file", file);
        let res = await this.$http.post('upload',formData)
        Editor.insertEmbed(cursorLocation, "image", res.data.url);
        resetUploader()
      },
      async feachCategory(){
        const res = await this.$http.get('rest/categories')
        this.category=res.data
        this.category.forEach(ele => {
          if (!ele.parent) {
            this.pagedata.push(ele)
          }
        });
        this.pagedata.forEach(e => {
          e.children=[]
          for (const ele of this.category) {
            if (ele.parent) {
              if (ele.parent.title===e.title) {
                e.children.push(ele)
              }
            }
          }
        });
        this.articlecategory=this.pagedata[1].children
      },
      async feach(){
        const res = await this.$http.get(`rest/articles/${this.id}`)
        this.model=res.data
      },
      onSubmit() {
        console.log('start!');
      },
      async saveArticle(){
        let res
        if (this.id) {//编辑
          res = await this.$http.put(`rest/articles/${this.id}`,this.model)
        }else{//新建
          res = await this.$http.post('rest/articles',this.model)
        } 
        this.$router.push('/articles/list')
        console.log(res.data);
        this.$message({
            message: '保存成功',
            type: 'success'
        });
      },
    }
  }
</script>
<style lang="css">

</style>